const multer = require('multer');
const path = require('path');

function createMulterInstance(destination) {
  return multer({
    storage: multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, destination);
      },
      filename: function (req, file, cb) {
        file.originalname = Buffer.from(file.originalname, 'latin1').toString('utf8');
        let type = file.originalname.replace(/.+\./, '.');

        if (['.png', '.jpg', '.jpeg'].includes(type.toLowerCase())) {
          cb(null, file.originalname + '-' + Date.now() + type);
        } else {
          cb(null, ''); // 不保存该文件
        }
      }
    })
  });
}

const addcarduploadPath = path.join(path.resolve(__dirname, '../'), 'data/uploads/img');
const userheaduploadPath =path.join(path.resolve(__dirname, '../'), 'data/uploads/userimg');
const bgcuploadPath =path.join(path.resolve(__dirname, '../'), 'data/uploads/bgcimg');
const addcardupload = createMulterInstance(addcarduploadPath);
const userheadupload = createMulterInstance(userheaduploadPath);
const bgcupload = createMulterInstance(bgcuploadPath);
module.exports = {addcardupload,userheadupload,bgcupload};